import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;

// HTTP请求类
public class HttpClientUtils {
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 发送HttpPost请求，参数为map
     * @param url
     * @param jsonObject
     * @return
     */
    public static String sendHttpPost(String url, JSONObject jsonObject) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String responseBody = null;
        try {
            // 设置请求头和请求体
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
            entity.setContentType(String.valueOf(httpPost.getHeaders("Content-Type")));
            httpPost.setEntity(entity);
            // 发送POST请求
            response = httpclient.execute(httpPost);
            // 处理HTTP异常
            int statusCode = response.getStatusLine().getStatusCode();
            responseBody = EntityUtils.toString(response.getEntity(), "utf-8");
            if (statusCode == 400 || statusCode == 404 || statusCode == 500) {
                // 抛出自定义异常
                throw new HttpClientException("Bad Request", statusCode, responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseBody;
    }

}
